<template>
  <div class="app-container">
    <!--头部区域-->
    <el-card class="operate-top-card" shadow="never">
      <div>
        <i
          class="el-icon-search"
          style="font-size: 18px; margin-right: 3px"
        ></i>
        <span>筛选搜索</span>
        <el-button
          class="btn-find"
          size="mini"
          type="primary"
          style="float: right; margin-left: 10px"
          @click="handleSearchList"
        >
          查询用户
        </el-button>
        <el-button
          class="btn-clear"
          size="mini"
          style="float: right"
          @click="handleResetSearch"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 50px">
        <el-form
          ref="productCateForm"
          :model="listQuery"
          label-width="150px"
          :inline="true"
        >
          <el-form-item label="输入账号：">
            <el-input
              v-model="listQuery.username"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <div>
      <!--头部区域-->
      <el-card class="operate-top-card" shadow="never">
        <i
          class="el-icon-s-order"
          style="font-size: 18px; margin-right: 3px"
        ></i>
        <span>管理员列表</span>
        <el-button class="btn-add" size="mini" @click="handleAdd()"
          >添加</el-button
        >
      </el-card>
      <!--内容区域-->
      <div class="table-container">
        <el-table
          ref="multipleTable"
          :data="list"
          v-loading="listLoading"
          border
          style="width: 100%"
        >
          <el-table-column label="序号" width="60" align="center">
            <template slot-scope="scope">{{
              scope.$index + 1 + (listQuery.pageNum - 1) * listQuery.pageSize
            }}</template>
          </el-table-column>
          <el-table-column label="管理员账户" width="100" align="center">
            <template slot-scope="scope">{{ scope.row.username }}</template>
          </el-table-column>
          <el-table-column label="管理员姓名" width="120" align="center">
            <template slot-scope="scope">{{ scope.row.nickname }}</template>
          </el-table-column>
          <el-table-column label="邮箱" width="160" align="center">
            <template slot-scope="scope">{{
              scope.row.email ? scope.row.email : "暂无"
            }}</template>
          </el-table-column>
          <el-table-column label="创建时间" width="200" align="center">
            <template slot-scope="scope">{{
              scope.row.createtime ? scope.row.createtime : "暂无"
            }}</template>
          </el-table-column>
          <el-table-column label="最后登录" width="200" align="center">
            <template slot-scope="scope">{{
              scope.row.logintime ? scope.row.logintime : "暂无数据"
            }}</template>
          </el-table-column>
          <el-table-column label="是否启用" width="100" align="center">
            <template slot-scope="scope">
              <el-switch
                :disabled="scope.row.id === 1"
                @change="handleShowStatusChange(scope.$index, scope.row)"
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="scope.row.id === 1"
                @click="handleSelectRole(scope.$index, scope.row)"
              >
                分配角色
              </el-button>
              <el-button
                size="mini"
                :disabled="scope.row.id === 1"
                @click="handleUpdate(scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                :disabled="scope.row.id === 1"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!--dialog面板-->
      <el-dialog
        :title="isEdit ? '编辑管理员' : '添加管理员'"
        :visible.sync="dialogVisible"
        width="40%"
        center
      >
        <el-form
          :model="admin"
          ref="adminForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="账号: ">
            <el-input
              type="text"
              v-model="admin.username"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名: ">
            <el-input
              type="text"
              v-model="admin.nickname"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱: ">
            <el-input
              type="text"
              v-model="admin.email"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码: ">
            <el-input
              type="password"
              v-model="admin.password"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注: ">
            <el-input
              type="textarea"
              :row="5"
              v-model="admin.note"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否启用: ">
            <el-radio-group v-model="admin.status">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- dialog面板 -->
      <el-dialog
        title="分配角色"
        :visible.sync="roleDialogVisible"
        width="30%"
        center
      >
        <el-select
          v-model="allocRoleIds"
          multiple
          placeholder="请选择"
          style="width: 90%"
        >
          <el-option
            v-for="item in allRoleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRoleDialogConfirm()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getAdminList,
  updateAdmin,
  addAdmin,
  deleteAdmin,
  getRoleList,
  getRoleWithAdmin,
  editRoleWithAdmin,
} from "../../../../api/adminApi";
import md5 from "blueimp-md5";
import config from "../../../config/config";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  username: "",
};
const defaultAdmin = {
  id: null,
  username: "",
  password: "",
  email: "",
  nickname: "",
  note: "",
  status: 1,
};
export default {
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery), //显示 搜素 数据存放
      listLoading: false, //数据加载圈
      list: [], //表格数据存放
      total: 0,
      dialogVisible: false, //控制 编辑 添加 面板是否显示
      admin: Object.assign({}, defaultAdmin), //弹框中数据
      roleDialogVisible: false, //角色分配面板
      allocRoleIds: "", //分配面板分配数据
      allRoleList: "", //分配面板下滑菜单数据
      isEdit: false,
      allocAdminId: "", //用户id
      passwordBefore: "", // 编辑之前的密码
    };
  },
  created() {
    this.getList();
    this.getAllRoleList(); //获取分配角色中的所有角色
  },
  methods: {
    //获取分配角色中的所有角色
    getAllRoleList() {
      getRoleList({ pageNum: 1, pageSize: 1000 }).then((res) => {
        console.log(res);
        if (res.status == 1) {
          this.allRoleList = res.data.list;
        }
      });
    },
    //获取表格数据源
    getList() {
      this.listLoading = true;
      getAdminList(this.listQuery).then((res) => {
        if (res.status == 1) {
          this.list = res.data.list;
          this.total = res.data.total;
          this.listLoading = false;
        }
      });
    },
    //查询用户
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //重置
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    //添加
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = Object.assign({}, defaultAdmin);
    },
    //是否启用
    handleShowStatusChange(index, row) {
      this.$confirm("是否修改角色启用状态, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateAdmin({ id: row.id, status: row.status }).then((res) => {
            if (res.status === 1) {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
            } else {
              this.$message.error("修改失败");
            }
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
          this.getList();
        });
    },
    //分配角色
    handleSelectRole(index, row) {
      this.roleDialogVisible = true;
      this.allocAdminId = row.id;
      this.getRoleListByAdmin(row.id);
    },
    //根据Id获得用户所分配到的权限
    getRoleListByAdmin(id) {
      getRoleWithAdmin({ id: id }).then((res) => {
        console.log(res);
        if (res.status == 1) {
          let allocRoleIdsStr = res.data.roleid;
          console.log(allocRoleIdsStr);
          this.allocRoleIds = [];
          let tempArr = [];
          if (allocRoleIdsStr != null && allocRoleIdsStr.length > 0) {
            tempArr = allocRoleIdsStr.split(",");
            for (let i = 0; i < tempArr.length; i++) {
              this.allocRoleIds.push(Number(tempArr[i]));
            }
          }
        }
      });
    },
    //编辑
    handleUpdate(index, row) {
      this.passwordBefore = row.password;
      this.dialogVisible = true;
      this.isEdit = true;
      this.admin = row;
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("是否删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteAdmin({ id: row.id }).then((res) => {
            if (res.status === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message.error("修删除失败");
            }
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    //编辑 添加 确定
    handleDialogConfirm() {
      let password = this.admin.password;
      if (this.isEdit) {
        //编辑
        console.log(this.admin);

        if (password !== this.passwordBefore) {
          this.admin.password = md5(password, config.KEY);
        }
        updateAdmin(this.admin).then((res) => {
          if (res.status == 1) {
            this.$message.success("编辑成功");
            this.dialogVisible = false;
            this.getList();
          } else {
            this.$message.error("编辑失败");
          }
        });
      } else {
        //添加
        this.admin.password = md5(password, config.KEY);
        addAdmin(this.admin).then((res) => {
          if (res.status == 1) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.getList();
          } else {
            this.$message.error("添加失败");
          }
        });
      }
    },
    //分配角色面板确定
    handleRoleDialogConfirm() {
      let roleid = this.allocRoleIds.join(",");
      editRoleWithAdmin({ id: this.allocAdminId, roleid }).then((res) => {
        if (res.status == 1) {
          this.$message.success("分配角色成功");
          this.roleDialogVisible = false;
        } else {
          this.$message.error("分配角色失败");
        }
      });
    },
  },
};
</script>

<style>
</style>